import 'dart:async';

import 'package:flutter/material.dart';
import "package:get/get.dart";

import '../../../../apis/maintenance.dart';
import '../../../../components/photo_preview/fade_foute.dart';
import '../../../../components/photo_preview/photo_preview.dart';
import '../../../../components/status/toast.dart';
import '../../../../config/base.dart';
import '../../../../controller/gather_ctrl.dart';
import '../../../../controller/network/bridge.dart';
import '../../../../controller/network/network_ctrl.dart';
import '../../../../model/bean/todo_details_bean.dart';
import '../typing/divide_upload_type.dart';

class DetailsCtrl extends GatherCtrl {
  // 路由参数
  static String _id;

  // 查看网络状态
  final _nc = Get.find<NetworkCtrl>();

  // 标记符号（用于检查请求完成后无数据组件与数据组件之的切换）
  final MARKSYMBOL = false.obs;

  // 组件是否初始化完成
  RxBool isInitComplete = false.obs;

  // 页面数据
  final tdData = Rx<TodoDetailsBean>();

  // 图片集合（用于预览）
  final rls = RxList<String>([]);

  // 存储楼栋图片
  final building = RxList<String>([]);

  // 存储电梯井图片
  final elevatorShaft = RxList<String>([]);

  @override
  void onInit() {
    // 创建网络变化观察
    Bridget.createNetworkCtrl(this);

    // -
    _id = Get.arguments['id'];

    // 请求详情
    readTodoDetails(Get.arguments['id']);
  }

  @override
  void onClose() {
    // 移除观察
    Bridget.delNetworkCtrl(this);
  }

  @override
  void modify() {
    // 网络恢复正常时执行当前函数
    if (_nc.networkStatus.value) readTodoDetails(_id);
  }

  /// 读取今日待办详情（维保）
  /// * [id] String|维保id|必填
  void readTodoDetails(String id) async {
    // 执行请求
    TodoDetailsBean result = await Maintenance.queryTodoDetails({"id": id});

    if (result != null) {
      tdData.value = result;
      MARKSYMBOL.value = true;

      // print(tdData);

      //print(tdData.value.villageName);
    }

    // 标记页面加载状态（初始化）
    if (!isInitComplete.value) isInitComplete.value = true;
  }

  /// 完成待办事项
  void onCompleteTodo() async {
    // 数据校验
    if (building.value.isEmpty) {
      Toast.fail(title: '未检出楼栋照片');
      return;
    }

    if (elevatorShaft.value.isEmpty) {
      Toast.fail(title: '未检出电梯井照片');
      return;
    }

    // 定义参数
    Map<String, dynamic> data = {
      "id": _id,
      "buildingPhotoPath": building.value.join(','),
      "shaftPhotoPath": elevatorShaft.value.join(',')
    };

    //print(data);

    // 提交数据
    try {
      String result = await Maintenance.completeTodo(data);

      // 成功提示
      Timer(Duration(milliseconds: 500), () {
        Toast.success(title: result);
      });
      // 返回上一步（通知需要更新）
      Get.back(result: true);
    } catch (e) {}
  }

  /// 读取图片上传后的路径
  /// * [list] List<String>|已上传图的路径集合|必填
  /// * [type] DivideUploadType|操作类型|必填
  void readUpLoadImgsResult(List<String> list, DivideUploadType type) {
    // BaseConfig.BASEURL.IMG['m1']
    switch (type) {
      case DivideUploadType.BUILDING:
        building.value = List.from(list.obs);
        break;
      case DivideUploadType.ELEVATORSHAFT:
        elevatorShaft.value = List.from(list.obs);
        break;
    }
  }

  /// 查看图片
  /// * [i] int|图片下标|必填
  /// * [type] DivideUploadType|操作类型|必填
  void reviewImages(int i, DivideUploadType type) {
    // 存储图片基础路径
    String _base = BaseConfig.BASEURL.IMG['m1'];

    // 构建图片集合
    switch (type) {
      case DivideUploadType.BUILDING:
        rls.value = List.from(building.value);
        break;
      case DivideUploadType.ELEVATORSHAFT:
        rls.value = List.from(elevatorShaft.value);
        break;
    }

    // 补充前缀
    if (rls.value.length > 0) {
      for (int i = 0; i < rls.value.length; i++) {
        // "${BaseConfig.BASEURL.IMG['m1']}${rls.value[i]}"
        rls.value[i] = rls.value[i].startsWith(_base)
            ? rls.value[i]
            : "${_base}${rls.value[i]}";
      }
    }

    // 查看图片
    Navigator.of(Get.context).push(
      FadeRoute(
        page: PhotoPreview(
          images: rls,
          index: i,
          heroTag: rls[i],
        ),
      ),
    );
  }
}
